﻿using System;
using System.Windows.Forms;

namespace ContagemFieiras
{
    public partial class frmLogin : Form
    {
        readonly frmFieiras _fieiras = new frmFieiras();
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtNome.Text))
            {
                Program.Entrada.lblStatus.Text = "Utilizador: " + txtNome.Text;
                Program.Entrada.btnLock.Image = Properties.Resources.UNLOCKED;

                _fieiras.MdiParent = Application.OpenForms["frmEntrada"];
                _fieiras.Show();

                FormClosing -= new FormClosingEventHandler(frmLogin_FormClosing);
                Close();
            }
            else
            {
                txtCodigo.Focus();
                MessageBox.Show("Sem utilizador definido!", "Erro");
            }
        }

        private void btCancelar_Click(object sender, EventArgs e)
        {
            FormClosing -= new FormClosingEventHandler(frmLogin_FormClosing);
            Application.Exit();
            txtCodigo.Focus();
        }

        private void frmLogin_Load(object sender, EventArgs e)
        {
            TopMost = true;                        
            bool Cancelar = true;

            foreach (Form frm in Application.OpenForms)
            {
                if (frm.Name != "frmEntrada" && frm.Name != "frmLogin") Cancelar = false;
            }
            if (Cancelar) btCancelar.Enabled = true;
            else btCancelar.Enabled = false;
        }

        private void txtCodigo_KeyUp(object sender, KeyEventArgs e)
        { if (e.KeyCode == Keys.Enter) btnLogin_Click(sender, e); }

        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        { e.Cancel = true; }

        private void txtCodigo_TextChanged(object sender, EventArgs e)
        {
            if (frmEntrada.dvUsers != null)
                frmEntrada.dvUsers.RowFilter = string.Format("Codigo ='{0}'", txtCodigo.Text);

            if (frmEntrada.dvUsers.Count > 0) txtNome.Text = frmEntrada.dvUsers[0].Row[1].ToString();
            else txtNome.Clear();
        }

        private void lblVirtualkeyboard_Click(object sender, EventArgs e)
        {
            try
            { System.Diagnostics.Process.Start("OSK.exe"); }
            catch (Exception ex)
            { MessageBox.Show(ex.Message); }
        }
    }
}
